package com.example.petadopt.ui.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.AdoptDao;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.entity.Adopt;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.ui.activity.AdoptionGuideActivity;
import com.example.petadopt.ui.activity.PetDetailActivity;
import com.example.petadopt.ui.adapter.BannerAdapter;
import com.example.petadopt.ui.adapter.HotPetAdapter;
import com.example.petadopt.utils.CurrentUserUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HomeFragment extends Fragment {

    private static final int BANNER_DELAY = 3000; // 3秒切换一次
    private final Handler handler = new Handler();
    private ViewPager2 viewPagerBanner;
    private LinearLayout llDots;
    private RecyclerView rvHotPets;
    private LinearLayout llAdoptionGuide;
    private List<Pet> allPetList = new ArrayList<>();
    private List<Pet> bannerPetList = new ArrayList<>();
    private List<Pet> hotPetList = new ArrayList<>();
    private BannerAdapter bannerAdapter;
    private HotPetAdapter hotPetAdapter;
    private Runnable bannerRunnable;
    private int currentBannerPosition = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        initAdapter();
        initListener();
        return view;
    }

    /**
     * 初始化视图
     */
    private void initView(View view) {
        viewPagerBanner = view.findViewById(R.id.viewpager_banner);
        llDots = view.findViewById(R.id.ll_dots);
        rvHotPets = view.findViewById(R.id.rv_hot_pets);
        llAdoptionGuide = view.findViewById(R.id.ll_adoption_guide);

        // 设置RecyclerView
        rvHotPets.setLayoutManager(new LinearLayoutManager(getContext()));
        rvHotPets.setNestedScrollingEnabled(false);
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        // 轮播图适配器
        bannerAdapter = new BannerAdapter();
        viewPagerBanner.setAdapter(bannerAdapter);

        // 热门宠物适配器
        hotPetAdapter = new HotPetAdapter();
        rvHotPets.setAdapter(hotPetAdapter);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        // 领养须知点击事件
        llAdoptionGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), AdoptionGuideActivity.class);
                startActivity(intent);

            }
        });

        // 轮播图点击事件
        bannerAdapter.setOnBannerClickListener(new BannerAdapter.OnBannerClickListener() {
            @Override
            public void onBannerClick(Pet pet) {
                Intent intent = new Intent(getContext(), PetDetailActivity.class);
                intent.putExtra("pet_id", pet.getId());
                startActivity(intent);
            }
        });

        // 热门宠物点击事件
        hotPetAdapter.setOnItemClickListener(new HotPetAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Pet pet) {
                Intent intent = new Intent(getContext(), PetDetailActivity.class);
                intent.putExtra("pet_id", pet.getId());
                startActivity(intent);
            }

            @Override
            public void onAdoptClick(View v, Pet pet) {
                AlertDialog dialog = new AlertDialog.Builder(getContext())
                        .setTitle("申请领养")
                        .setMessage("确定申请领养 " + pet.getName() + " 吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Button btnAdopt = (Button) v;
                                applyForAdoption(btnAdopt, pet);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create();
                dialog.show();
            }
        });

        // ViewPager2页面切换监听
        viewPagerBanner.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentBannerPosition = position;
                updateDots(position);
            }
        });
    }


    /**
     * 申请领养
     */
    private void applyForAdoption(Button btnAdopt, Pet pet) {
        Long userId = CurrentUserUtils.getCurrentUser().getId();
        if (userId == -1) {
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (pet == null || pet.getId() == null) {
            Toast.makeText(getContext(), "宠物信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查宠物是否已被领养
        if (pet.getIsAdopted() != null && pet.getIsAdopted()) {
            Toast.makeText(getContext(), "该宠物已被领养", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建领养记录
        Adopt adopt = new Adopt();
        adopt.setPetId(pet.getId());
        adopt.setAdoptUserId(userId);
        // 使用当前时间作为领养时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        adopt.setAdoptTime(sdf.format(new Date()));

        Result<Void> result = AdoptDao.addAdopt(adopt);
        if (result.isSuccess()) {
            pet.setIsAdopted(true);
            pet.setAdoptUserId(userId);
            btnAdopt.setEnabled(false);
            btnAdopt.setText("已被领养");
            Toast.makeText(getContext(), "领养成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "领养申请失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载数据
     */
    private void loadData() {
        Result<List<Pet>> result = PetDao.getAllPets(CurrentUserUtils.getCurrentUser().getId());

        if (result.isSuccess()) {
            allPetList = result.getData();

            if (allPetList.size() > 0) {
                // 随机打乱宠物列表
                List<Pet> shuffledList = new ArrayList<>(allPetList);
                Collections.shuffle(shuffledList);

                // 选择3个宠物作为轮播图
                int bannerCount = Math.min(shuffledList.size(), 3);
                bannerPetList = shuffledList.subList(0, bannerCount);
                bannerAdapter.setPetList(bannerPetList);

                // 初始化轮播图指示点
                setupDots(bannerCount);

                // 开始自动轮播
                startBannerAutoScroll();

                // 选择5个宠物作为热门领养
                int hotPetCount = Math.min(shuffledList.size(), 5);
                // 避免重复，从剩余的宠物中选择
                int startIndex = bannerCount;
                if (shuffledList.size() > bannerCount) {
                    hotPetList = shuffledList.subList(startIndex, Math.min(startIndex + hotPetCount, shuffledList.size()));
                } else {
                    // 如果宠物不够，就重复使用
                    hotPetList = new ArrayList<>(shuffledList);
                }
                hotPetAdapter.setPetList(hotPetList);
            } else {
                Toast.makeText(getContext(), "暂无宠物数据", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getContext(), "加载宠物数据失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 设置轮播图指示点
     */
    private void setupDots(int count) {
        llDots.removeAllViews();

        for (int i = 0; i < count; i++) {
            ImageView dot = new ImageView(getContext());
            dot.setImageResource(R.drawable.dot_selector);
            dot.setSelected(i == 0); // 默认选中第一个

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.setMarginEnd(8); // 设置点之间的间距
            dot.setLayoutParams(params);

            llDots.addView(dot);
        }
    }

    /**
     * 更新指示点状态
     */
    private void updateDots(int position) {
        for (int i = 0; i < llDots.getChildCount(); i++) {
            ImageView dot = (ImageView) llDots.getChildAt(i);
            dot.setSelected(i == position);
        }
    }

    /**
     * 开始自动轮播
     */
    private void startBannerAutoScroll() {
        bannerRunnable = new Runnable() {
            @Override
            public void run() {
                if (bannerPetList.size() > 1) {
                    // 修改轮播方向：从左往右
                    if (currentBannerPosition == 0) {
                        // 当前位置为第一个，设置为最后一个
                        currentBannerPosition = bannerPetList.size() - 1;
                    } else {
                        // 否则向前移动一位
                        currentBannerPosition--;
                    }
                    viewPagerBanner.setCurrentItem(currentBannerPosition, true);
                }
                handler.postDelayed(this, BANNER_DELAY);
            }
        };
        handler.postDelayed(bannerRunnable, BANNER_DELAY);
    }

    /**
     * 停止自动轮播
     */
    private void stopBannerAutoScroll() {
        if (handler != null && bannerRunnable != null) {
            handler.removeCallbacks(bannerRunnable);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        stopBannerAutoScroll();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
        if (bannerPetList.size() > 0) {
            startBannerAutoScroll();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopBannerAutoScroll();
    }
} 